﻿using HotelManagementClient.Model;
using HotelManagementClient.Utlis;
using HotelManagementClient.ViewModel;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using QRCoder;
using System.IO;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace HotelManagementClient
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        
        MqttClient m_MqttClient = new MqttClient();
        public static string des3Key= "Tt3rLPrDIVIhXqAz";// 长度控制为16，作为3DES加密用的key
        //public static string des3Key = "ygs_"+DateUtil.Nowd();// 长度控制为16，作为3DES加密用的key

        public static string UUID;
        public static bool scan_bool=false;

        //private string UpgradeServerAddress = "192.168.0.55";//远程服务器地址
        private string UpgradeServerAddress = "120.79.63.6";//远程服务器地址
        //private int UpgradeServerPort = 1883;//远程服务器端口
        private int UpgradeServerPort = 8091;//远程服务器端口
        private string UpgradeServerUser = "";//远程服务器账号
        private string UpgradeServerPwd = "";//远程服务器密码

        public Login()
        {
            InitializeComponent();
        }


        private void CloseWindow_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        /// <summary>
        /// 登录按钮
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Button_Click(object sender, RoutedEventArgs e)
        {
            //记住密码
            string isRemember = ckbRemember.IsChecked.Value.ToString();
            string username_text = UserName.Text;
            string password_text = Password.Password.ToString();
            string code_text = Code.Text;
            
           

            if (string.IsNullOrEmpty(username_text))
            {
                MessageBox.Show("请填写登录账号信息");
                return;
            }

            if (string.IsNullOrEmpty(password_text))
            {
                MessageBox.Show("请填写登录密码信息");
                return;
            }

            if (string.IsNullOrEmpty(code_text))
            {
                MessageBox.Show("请填写验证码信息");
                return;
            }

            var postData = new { username = username_text, password = password_text,code=code_text,uuid=UUID };
            string loginStr = HttpPost.Postdata(JsonConvert.SerializeObject(postData), StrUtils.login_url);
            if (string.IsNullOrEmpty(loginStr))
            {
                MessageBox.Show("登录失败");
                GetVerifiCode();
                return;
            }

            JObject obj =JObject.Parse(loginStr);
            if (Convert.ToInt16(obj["code"]) == 200)
            {
                string ACCESS_TOKEN = obj["data"].Value<string>("access_token");
                int DEFAULTPROPERTYID = obj["data"].Value<int>("defaultPropertyId");
                int USERTYPE = obj["data"].Value<int>("userType");

                //保存mac
                MacAddressUtil macAddressUtil = new MacAddressUtil();
                string mac = macAddressUtil.GetMacByIpConfig();
                AppConfigUtil.SetValue("SystemInfo", "mac", Encryptor.EncryptData(mac, des3Key));


                //设置登录用户信息
                AppConfigUtil.SetValue("LoginUser", "hotelId", Encryptor.EncryptData(DEFAULTPROPERTYID.ToString(), des3Key));
                AppConfigUtil.SetValue("LoginUser", "accessToken", Encryptor.EncryptData(ACCESS_TOKEN, des3Key));
                AppConfigUtil.SetValue("LoginUser", "userType", Encryptor.EncryptData(USERTYPE.ToString(), des3Key));

                //获取物业信息
                if (!string.IsNullOrEmpty(Convert.ToString(DEFAULTPROPERTYID)))
                {
                    string hotelResult = HttpGet.Get(StrUtils.login_default_hotel_url + DEFAULTPROPERTYID);
                    if (string.IsNullOrEmpty(loginStr))
                    {
                        MessageBox.Show("登录失败:酒店信息不存在");
                        GetVerifiCode();
                        return;
                    }
                    JObject objHotel = JObject.Parse(hotelResult);
                    if (Convert.ToInt32(objHotel["code"])  != 200)
                    {
                        MessageBox.Show("登录失败:" + objHotel["msg"]);
                        GetVerifiCode();
                        return;
                    }

                    //设置酒店名称
                    AppConfigUtil.SetValue("HotelInfo", "hotelName", Encryptor.EncryptData(objHotel["data"].Value<string>("propertyName"), des3Key));
                    //设置酒店地址
                    AppConfigUtil.SetValue("HotelInfo", "hotelAddress", Encryptor.EncryptData(objHotel["data"].Value<string>("address"), des3Key));
                }
                else
                {
                    MessageBox.Show("登录失败:酒店信息获取失败");
                    return;
                }

                string loginUserResult = HttpGet.Get(StrUtils.login_user_url+ username_text);
                if (string.IsNullOrEmpty(loginUserResult))
                {
                    MessageBox.Show("登录用户信息错误");
                }
                JObject objLoginUser = JObject.Parse(loginUserResult);
                if (Convert.ToInt32(objLoginUser["code"]) == 200)
                {
                    AppConfigUtil.SetValue("LoginUser", "loginUserName", Encryptor.EncryptData(objLoginUser["data"].Value<string>("userName"), des3Key));
                    AppConfigUtil.SetValue("LoginUser", "loginNickName", Encryptor.EncryptData(objLoginUser["data"].Value<string>("nickName"), des3Key));
                    AppConfigUtil.SetValue("LoginUser", "loginAvatar", Encryptor.EncryptData(objLoginUser["data"].Value<string>("avatar"), des3Key));
                    AppConfigUtil.SetValue("LoginUser", "loginRealName", Encryptor.EncryptData(objLoginUser["data"].Value<string>("realName"), des3Key));
                }
                else
                {
                    MessageBox.Show("登录失败:" + objLoginUser["msg"]);
                    return;
                }
                //设置pms地址
                AppConfigUtil.SetValue("ExternalLinks", "T3PMS", "https://www.ygs.cc");


                //是否记录用户名密码
                AppConfigUtil.SetValue("LoginUser", "isRemember", Encryptor.EncryptData(isRemember, des3Key));
                if (isRemember.Equals("True"))
                {
                    //保存用户名及密码
                    AppConfigUtil.SetValue("LoginUser", "username", Encryptor.EncryptData(username_text, des3Key));
                    AppConfigUtil.SetValue("LoginUser", "password", Encryptor.EncryptData(password_text, des3Key));
                }
                else
                {
                    //清空登录的用户名及密码
                    AppConfigUtil.SetValue("LoginUser", "username", "");
                    AppConfigUtil.SetValue("LoginUser", "password", "");
                }

                MainWindow mainWindow = new MainWindow();
                Window window = Window.GetWindow(this);//关闭父窗体
                window.Close();               
                mainWindow.Show();
            }
            else
            {
                MessageBox.Show("登录失败："+ obj["msg"]);
                GetVerifiCode();
                return;
            }  
        }

        /// <summary>
        /// 进入传统登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void TraditionalLoginBtn_Click(object sender, RoutedEventArgs e)
        {
            if(Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "isRemember"),des3Key).Equals("True"))
            {
                ckbRemember.IsChecked = true;
                string username =Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "username"), des3Key);
                string password =Encryptor.DecryptData(AppConfigUtil.GetValue("LoginUser", "password"), des3Key);
                UserName.Text = username;
                Password.Password=password;
            }
            else
            {
                ckbRemember.IsChecked = false;
            }
            GetVerifiCode();
        }


        /// <summary>
        /// 进入微信扫码登录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void QcLoginBtn_Click(object sender, RoutedEventArgs e)
        {
            GetQrCode();
        }

        /// <summary>
        /// 获取二维码
        /// </summary>
        private async void GetQrCode()
        {
            //获取二维码数据
            string qrData = HttpGet.Get(StrUtils.login_qr_code_url);
            if (!string.IsNullOrEmpty(qrData))
            {
                JObject obj = JObject.Parse(qrData);
                string qrStr = obj["data"].ToString();
                //主题 /jz/qr/lg/login_codeca03d644-80b8-4063-a771-faeb07e1e212

               
                var topicList = new List<string> { "/jz/qr/lg/" + qrStr };
                string clientId = "loginuser_" + StrUtils.GetRandomStr("1234567890", 8);
                //连接mqtt
                m_MqttClient.MqttClientCon(topicList, clientId);
                m_MqttClient.OnMessage += OnMessgae;

                //生成二维码
                //https://www.ygs.cc/jz/qr/lg/login_codeca03d644-80b8-4063-a771-faeb07e1e212
                string base64Img = ImgUtil.GetQrCodeImage(StrUtils.baseUrl.Replace("/prod-api", "") + "/jz/qr/lg/" + qrStr);
                JObject baseObj = JObject.Parse(base64Img);
                if (baseObj != null)
                {
                    ImageQc.Source = ImgUtil.ConvertToImageSource(baseObj["base64"].ToString());
                }

            }
        }

       
        /// <summary>
        /// 监听消息
        /// </summary>
        /// <param name="msg"></param>
        private void OnMessgae(string msg)
        {
            /*MessageBox.Show("登录回来的数据信息:"+msg);*/
            JObject lognData=JObject.Parse(msg);
            bool hasCode = lognData.Properties().Any(p => p.Name == "access_token");
            if(!hasCode)
            {
                return;
            }

            string ACCESS_TOKEN = lognData["access_token"].ToString();              
            int DEFAULTPROPERTYID = Convert.ToInt16(lognData["defaultPropertyId"]);
            int USERTYPE = Convert.ToInt16(lognData["userType"]);

            AppConfigUtil.SetValue("LoginUser", "hotelId", Encryptor.EncryptData(DEFAULTPROPERTYID.ToString(), des3Key));
            AppConfigUtil.SetValue("LoginUser", "accessToken", Encryptor.EncryptData(ACCESS_TOKEN, des3Key));
            AppConfigUtil.SetValue("LoginUser", "userType", Encryptor.EncryptData(USERTYPE.ToString(), des3Key));

            MacAddressUtil macAddressUtil = new MacAddressUtil();
            string mac = macAddressUtil.GetMacByIpConfig();
            AppConfigUtil.SetValue("SystemInfo", "mac", Encryptor.EncryptData(mac, des3Key));

            m_MqttClient.m_MqttClient.Dispose();


            App.Current.Dispatcher.Invoke((Action)(() =>
            {
                MainWindow mainWindow = new MainWindow();
                Window window = Window.GetWindow(this);//关闭父窗体
                window.Close();
                mainWindow.Show();
            }));

        }

        /// <summary>
        /// 获取验证码
        /// </summary>
        private void GetVerifiCode()
        {

            if (!NetWorkUtil.IsNetworkConnected)
            {
                MessageBox.Show("电脑当前无网络");
                return;
            }

            if (!NetWorkUtil.CheckWebConnection(StrUtils.login_code_url))
            {
                MessageBox.Show("无法连接服务器");
                return;
            }

            if (!NetWorkUtil.CheckUrlVisit(StrUtils.login_code_url))
            {
                MessageBox.Show("无法连接服务器");
            }

            string loginStr = HttpGet.Get(StrUtils.login_code_url);
            JObject obj = StrUtils.JosnToOjbect(loginStr);
            if (obj != null)
            {
                string imagebase64 = obj["img"].ToString();
                UUID = obj["uuid"].ToString();
                VerificationCode.Source = ImgUtil.ConvertToImageSource(imagebase64);
            }
        }

        /// <summary>
        /// 验证码点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void VerificationCode_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            GetVerifiCode();
        }

        /// <summary>
        /// 主窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            AppConfigUtil.SetValue("LoginUser", "hotelId", "");
            AppConfigUtil.SetValue("LoginUser", "accessToken", "");
            AppConfigUtil.SetValue("LoginUser", "userType", "");
            AppConfigUtil.SetValue("LoginUser", "loginUserName", "");
            AppConfigUtil.SetValue("LoginUser", "loginAvatar", "");
            AppConfigUtil.SetValue("LoginUser", "loginRealName", "");
            AppConfigUtil.SetValue("LoginUser", "loginNickName", "");

            AppConfigUtil.SetValue("HotelInfo", "hotelName", "");
            AppConfigUtil.SetValue("HotelInfo", "hotelAddress", "");


            MacAddressUtil macAddressUtil = new MacAddressUtil();
            string mac =macAddressUtil.GetMacByIpConfig();
            string systemMac = Encryptor.DecryptData(AppConfigUtil.GetValue("SystemInfo", "mac"), des3Key);

            if (string.IsNullOrEmpty(systemMac) || !mac.Equals(systemMac))
            {
                AppConfigUtil.SetValue("LoginUser", "isRemember", "");
                AppConfigUtil.SetValue("LoginUser", "username", "");
                AppConfigUtil.SetValue("LoginUser", "password", "");
            }
            
            HslCommunication.MQTT.MqttSyncClient client = new HslCommunication.MQTT.MqttSyncClient(new HslCommunication.MQTT.MqttConnectionOptions()
            {
                IpAddress = UpgradeServerAddress,//服务器程序所在电脑的ip地址
                Port = 1883,//端口
                            //Credentials = new HslCommunication.MQTT.MqttCredential(UpgradeServerUser,UpgradeServerPwd), // 如果配置了用户名及密码的话，就是这么设置
            });

            HslCommunication.OperateResult<string> readVersion = client.ReadRpc<string>("Services/GetClientApi", new { });
            if (readVersion.IsSuccess)
            {
                string currentVersion = Encryptor.DecryptData(AppConfigUtil.GetValue("Version", "version"), des3Key);
                if (string.IsNullOrEmpty(currentVersion))
                {
                    currentVersion = "1.0.0";
                }


                // 获取成功，和当前的版本号对比
                //if (new HslCommunication.BasicFramework.SystemVersion(readVersion.Content) > new HslCommunication.BasicFramework.SystemVersion(currentVersion))
                if (new Version(readVersion.Content) > new Version(currentVersion))
                {
                    MessageBoxResult vr = System.Windows.MessageBox.Show(currentVersion + " ✈ " + readVersion.Content + Environment.NewLine + "是否确认更新？", "新版", MessageBoxButton.OKCancel, MessageBoxImage.Question);

                    // 有了新版本，当然你这里可以跳过确认，强制更新
                    if (vr == MessageBoxResult.OK)// 如果是确定，就执行下面代码
                    {
                        // 确认更新，启动当前目录的更新程序
                        try
                        {
                            System.Diagnostics.Process.Start(System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Upgrade.exe"), UpgradeServerAddress + " " + UpgradeServerPort + " \"HotelManagementClient.exe\"");
                            System.Threading.Thread.Sleep(20);
                            Close();
                            AppConfigUtil.SetValue("Version", "version", Encryptor.EncryptData(readVersion.Content, des3Key));
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show("启动更新失败:" + ex.Message);
                            Close();
                        }
                    }
                }
            }

            //二维码
            GetQrCode();
        }

    }
}
